<template>
  <div class="updatePrice">
    <el-dialog
      v-model="visible.detail"
      :close-on-click-modal="false"
      title="商品改价"
      width="600px"
    >
      <el-form
        ref="ruleFormRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="订单应付价格" prop="price">
          <el-input v-model="form.price" disabled />
        </el-form-item>
        <el-form-item label="修改价格" prop="newPrice">
          <el-input
            v-model="form.newPrice"
            maxlength="9"
            @change="
              (val) => {
                scope.row.newPrice = parseFloat(val) ? parseFloat(val) : 1
              }
            "
          />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button
          type="primary"
          :loading="loading.submit"
          @click="changeOrderPrice"
        >确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script setup>
import { updateOrderPrice } from '@/api/order'
import { defineComponent, reactive, ref } from 'vue'

defineComponent({
  name: 'ChangePrice'
})

const emit = defineEmits(['success']);

let visible = reactive({
  detail: false,
});

let loading = reactive({
  submit: false,
})

const ruleFormRef = ref();
let form = ref({
  orderId: null,
  price: 0,
  newPrice: 0,
});
const rules = {
  newPrice: [
    { required: true, message: '请输入修改后的价格', trigger: 'blur' },
  ],
}

function show (row) {
  visible.detail = true
  form.value.orderId = row.orderId
  form.value.price = row.price
}
function cancel () {
  ruleFormRef.value.resetFields()
  visible.detail = false
}
function changeOrderPrice () {
  ruleFormRef.value.validate((valid) => {
    if (valid && !loading.submit) {
      loading.submit = true
      updateOrderPrice({
        orderId: form.value.orderId,
        price: form.value.newPrice,
      })
        .then((res) => {
          if (res.code === '') {
            ElMessage.success('修改成功')
            visible.detail = false
            emit('success')
          }
        })
        .catch((err) => {
          console.log(err)
        })
        .finally(() => {
          loading.submit = false
        })
    }
  })
}

defineExpose({
  show,
})
</script>